const Service = require("egg").Service;
const dayjs = require("dayjs");
const validateUtil = require('@jianghujs/jianghu/app/common/validateUtil');
const { TICKET_TYPE, ORDER_STATUS, DATE_FORMAT, TICKET_STATUS } = require("../constant/constant");
const { BizError, ERROR_INFO_ENUM } = require("../constant/error");
const _ = require('lodash');

const actionDataScheme = Object.freeze({
  handleCarRequestTicket: {
    type: 'object',
    additionalProperties: true,
    required: ['ticketId', 'ticketType', 'ticketContent', 'ticketStatus'],
    properties: {
      ticketId: { anyOf: [{ type: "string" }, { type: "number" }] },
      ticketType: { type: "string", enum: ['发车申请', '退车申请'] },
      ticketContent: { type: 'object' },
      ticketStatus: { type: 'string', enum: ['处理中', '完成', '拒绝'] },
    },
  },

  '发车申请': {
    type: 'object',
  },
  '退车申请': {
    type: 'object',
  },
});

class CarService extends Service {
  // 处理发车退车申请
  async handleCarRequestTicket(actionData) {
    const { jianghuKnex } = this.app;
    const { ctx } = this;

    const { dataList } = actionData
    const { userId, username } = this.ctx.userInfo

    //校验
    const ticketIds = _.map(dataList, 'ticketId');
    const ticketList = await jianghuKnex('ticket').whereIn('ticketId', ticketIds).select();
    if (ticketList.length !== dataList.length) {
      throw new BizError(errorInfoEnum.payment_ticket_request_not_exist);
    }
    if (_.find(ticketList, item => _.includes(['完成', '拒绝'], item.ticketStatus))) {
      throw new BizError(errorInfoEnum.payment_ticket_request_already_handle);
    }

    const ticketUpdateList = [];
    const dispatchInsertList = [];
    const basicUpdateData = {}
    const orderList = await jianghuKnex("order").select();

    let idSequence = await this.service.common.getIdSequence({table: 'dispatch'})

    _.map(dataList, item => {
      const { ticketContent, ticketType } = item
      validateUtil.validate(actionDataScheme.handleCarRequestTicket, item);
      validateUtil.validate(actionDataScheme[ticketType], ticketContent, '工单内容');

      ticketUpdateList.push({
        ticketId: item.ticketId,
        ticketStatus: '完成',
        ticketStatusAt: dayjs().format(DATE_FORMAT),
        ticketStatusByUserId: userId,
        ticketStatusByUser: username,
        carId: item.carId,
        orderId: item.orderId,
      })
      dispatchInsertList.push({
        dispatchId: `CD${idSequence}`,
        idSequence,
        contractId: ticketContent.contractId,
        carId: item.carId,
        carNumber: ticketContent.carNumber,
        dispatchStatus: item.ticketType === "发车申请" ? '发车' : '退车',
        currentKilometers: ticketContent.currentKilometers,
        dispatchFuel: ticketContent.dispatchFuel,
      })
      idSequence++

      const { status } = orderList.find(order => order.orderId == item.ticketContent.ticketBizId) || {}
      // 是否有支付订单

      orderList.find(order => order.orderId == item.ticketBizId) || {}
      item.orderActionData = {};

      switch (ticketType) {
        case TICKET_TYPE.DISPATCH:
          // 已付押金才能发车
          if (status !== ORDER_STATUS.PAY_DEPOSIT) {
            throw new BizError(ERROR_INFO_ENUM.INVALID_PROCESS);
          }
          item.orderActionData.status = ORDER_STATUS.DISPATCHED;
          // 发车后修改车辆状态
          item.operationStatus = '不可用'
          item.notOperationReason = '已发车'
          break;
        case TICKET_TYPE.RETURN:
          // 已发车之后才能退车
          if (status !== ORDER_STATUS.DISPATCHED) {
            throw new BizError(ERROR_INFO_ENUM.INVALID_PROCESS);
          }
          item.orderActionData.status = ORDER_STATUS.INSPECTED;
          item.operationStatus = '可用'
          item.notOperationReason = '已发车'
         
          break;
        default:
          throw new BizError(ERROR_INFO_ENUM.INVALID_PROCESS);
      }
    })


    await jianghuKnex.transaction(async trx => {


      if (dispatchInsertList.length > 0) {
        await trx("dispatch").jhInsert(dispatchInsertList, ctx)
      }

      for (const item of ticketUpdateList) {
        const { carId, orderId, ...itemData } = item
        await trx('ticket').where({ ticketId: item.ticketId }).jhUpdate(itemData, ctx);


        await trx("basic").where({ carId }).jhUpdate({
          operationStatus: item.operationStatus,
          notOperationReason: item.notOperationReason,
        });

        await trx("order").where({ orderId }).jhUpdate(item.orderActionData, ctx)
      }

    });
  }

}
module.exports = CarService;
